/*
 * Course:        COMP 380
 * Semester:      Summer 2012
 * Assignment:    Text To Speech
 * File Name:     SavedAudio.java
 * Author:        James Paul Pan
 * 				  Kenneth Wakeland
 * 				  Peter Xaymountry
 * Group #:		  Group #3
 */

package com.comp380.texttospeech;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.StreamCorruptedException;
import java.util.ArrayList; 
import com.comp380.texttospeech.R; 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast; 

public class SavedAudio extends Activity implements OnClickListener 
{  
	// Initialize the buttons variable.
	Button btnClearSaved, btnDone, btnNavMain, 
		   btnNavSaved, btnNavShare, btnNavImport;
	
	ArrayList<FileInformation> fileInfo = null;
	
	// Initialize the string variable to represent the directory.
	String test_to_speech_directory = "";
	
	// Initialize the string variable to represent the file path.
	String dataFilePath = "";
	
	@Override    
	public void onCreate(Bundle savedInstanceState) 
	{
		// Keep the screen orientation in portrait mode
    	super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    	
    	// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);     
		
		// Set the layout for this activity.
		setContentView(R.layout.saved_audio);   
		
		// kenny : add start 
		test_to_speech_directory = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separatorChar + getString(R.string.name_directory);
		dataFilePath = test_to_speech_directory + File.separatorChar + "FileInformationFile.dat";
		// kenny : add stop 
		
		// Pass the variables to correspond with the Delete All button.
		btnClearSaved = (Button) findViewById(R.id.btnClearSaved);
		
		// When the button is click it goes to the onClick method and delete
		// all saved audio track.
		btnClearSaved.setOnClickListener(this);

		// Pass the variables to correspond with the Done button.
		btnDone = (Button) findViewById(R.id.btnDoneSaved3);
		
		// When the button is click it goes to the onClick method and take
		// the user to the previous screen.
		btnDone.setOnClickListener(this);

		// Pass the variables to correspond with the Main button.
		btnNavMain = (Button) findViewById(R.id.btnNavMain3);
		
		// When the button is click it goes to the onClick method and take
		// the user to the Main screen.
		btnNavMain.setOnClickListener(this);
		
		// Pass the variables to correspond with the Saved button.
		btnNavSaved = (Button) findViewById(R.id.btnNavSaved3);
		
		// When the button is click it goes to the onClick method and take
		// the user to the Saved screen.
		btnNavSaved.setOnClickListener(this);

		// Pass the variables to correspond with the Share button.
		btnNavShare = (Button) findViewById(R.id.btnNavShare3);
		
		// When the button is click it goes to the onClick method and take
		// the user to the Share screen.
		btnNavShare.setOnClickListener(this);

		// Pass the variables to correspond with the Import button.
		btnNavImport = (Button) findViewById(R.id.btnNavImport3);
		
		// When the button is click it goes to the onClick method and take
		// the user to the Import screen.
		btnNavImport.setOnClickListener(this);
		
		displayList();				   
	}     

	/*
	 * This method will handle what happen when the user click on a particular 
	 * button.
	 *
	 * @param
	 * 	arg0 will handle which button was press.
	 */
	public void onClick(View arg0) 
	{
			//This switch statement will handle what each button will do.
            switch (arg0.getId()) 
            {
                case R.id.btnDoneSaved3:
                							// This method is part of the Activity package and you call this
                    						// when the main activity is done and should be close.
                    						finish();
                    						break;

                case R.id.btnNavMain3:
                							// Display a message that the user click on the Main button.
                    						Toast.makeText(getBaseContext(), "Going to Main screen", Toast.LENGTH_SHORT).show();
                    						
                    						// This will start the transition to the Main screen.
                    						startActivity(new Intent(this, Text_to_speechActivity.class));
                    						break;

                case R.id.btnNavShare3:
                							// Display a message that the user click on the Share button.
                    						Toast.makeText(getBaseContext(), "Going to Share screen", Toast.LENGTH_SHORT).show();
                    						
                    						// This will start the transition to the Share screen.
                    						startActivity(new Intent(this, share.class));
                    						break;

                case R.id.btnNavImport3:
                							// Display a message that the user click on the Import button.
                							Toast.makeText(getBaseContext(), "Going to Import Screen", Toast.LENGTH_SHORT).show();
                							
                							// This will start the transition to the Import screen.
                							startActivity(new Intent(this, importwindow.class));
                							break;

                case R.id.btnNavSaved3:
                							// Display a message that the user click on the Saved button.
                    						Toast.makeText(getBaseContext(), "Your already in the Saved screen", Toast.LENGTH_SHORT).show();
                    						break;

                case R.id.btnClearSaved : 
                							// Display a message that the user click on the delete all button.
											Toast.makeText(getBaseContext(), "You selected to delete all file", Toast.LENGTH_SHORT).show();
                    						
											// This call the deleteAllFiles which delete all the saved audio track.
											deleteAllFiles();
                    						break;
            }
	}
	
	/*
	 * This method will display the list of saved audio track.
	 */
	private void displayList()
	{
		// Initialize the InputSteam variable and set it to null.
		ObjectInputStream in = null;
		try 
		{
			// Pass the variable to represent the file path of the saved audio track.
			in = new ObjectInputStream(new FileInputStream(dataFilePath));
			
		} 
		catch (StreamCorruptedException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (FileNotFoundException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// If the file path is not null, it will display a list of saved audio track.
		if(in != null)
		{
			try 
			{
				// Set the fileInfo in to ArrayList
				fileInfo = (ArrayList<FileInformation>) in.readObject();
			} 
			catch (OptionalDataException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			catch (ClassNotFoundException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			catch (IOException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();	
			}
			
			// Initialize and set the ListView to the list view.
			final ListView lv = (ListView) findViewById(R.id.srListView);        
			
			// Add the file info array to the list view 
			lv.setAdapter(new MyBaseAdapter(this, fileInfo));
			
			// set the On Click Listener for the list view for the
			lv.setOnItemClickListener(new OnItemClickListener() 
			{            
				
				//@Override            
				public void onItemClick(AdapterView<?> a, View v, int position, long id) 
				{  
					// The list view of position
					Object o = lv.getItemAtPosition(position);
					
					// Set the Object to a FileInformation
					FileInformation fullObject = (FileInformation) o;
					
					// Pass the file name of the fullObject and pass it to a string.
					String test = fullObject.getDestinationFileName();
					
					// Initialize and create a new intent to the PlayAudio class.
					Intent intent = new Intent(getBaseContext(),PlayAudio.class);
					
					// Create a new bundle to pass information to another activity.
					Bundle b = new Bundle();
					
					// Save the file path of the object to be pass through the bundle.
					b.putString("File", test);
					
					// Put the string to the intent.
					intent.putExtras(b);
					
					// This will start the transition to the PlayAudio screen.
					startActivity(intent);     
				}        
			}); 
			
			// Set the delete for the Long Click.
			lv.setOnItemLongClickListener(new OnItemLongClickListener()
			{
				//@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) 
				{
					// The list view of Position.
					Object o = lv.getItemAtPosition(arg2);
					
					// Set the Object to a FileInformation.
					final FileInformation fullObject = (FileInformation) o;
					
					// Build the On Click Listener for the builder delete.
					final DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() 
					{ 
			  		   // @Override 
			  		    public void onClick(DialogInterface dialog, int which) 
			  		    { 
			  		        switch (which)
			  		        { 
			  		        	// If the user select Yes then delete.
			  		         	case DialogInterface.BUTTON_POSITIVE:
			  		         											deleteAudioFile(fullObject.getDestinationFileName());
			  		         											removeIndividualFile(arg2);	  		        	
			  		         											break;			  		        	
                                
			  		         	// If the user select No then do nothing.
			  		         	case DialogInterface.BUTTON_NEGATIVE: 
			  		         											break; 
			  		        }
			  		    }
					};
					
					// Show the "want to delete" builder to the user.
					AlertDialog.Builder builder = new AlertDialog.Builder(SavedAudio.this); 
			        	builder.setMessage("Are you sure you want to delete " + "\"" + fullObject.getPrevName() + "\"?")
			        	.setPositiveButton("Yes", dialogClickListener)
			        	.setNegativeButton("No", dialogClickListener).show(); 			        
			  		            
					return false;
				}
			});
		}
	}
	
	/*
	 * This method will delete the audio track.
	 */
	private void deleteAudioFile(String strFilePath)
	{
		// Initialize and create a new file with the file path.
		File mfile = new File(strFilePath);
		
		// This will delete that file.
		mfile.delete();
	}
	
	/*
	 * This method will remove individual file that the user selected.
	 */
	private void removeIndividualFile(int position)
	{
		// Initialize a new ObjectInput and set it to null.
		ObjectInputStream in = null;
		
		try 
		{
			// This will get the data file.
			in = new ObjectInputStream(new FileInputStream(dataFilePath));
		} 
		catch (StreamCorruptedException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (FileNotFoundException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// If the Input Stream is null then delete the line at position.
		if(in == null)
		{
			fileInfo.remove(position);
			
			// Display a message to the user that the file been deleted.
			Toast.makeText(getBaseContext(), "File deleted!", Toast.LENGTH_SHORT).show();
			
			// Call the save Array To Disk to resave the new data.
			saveArrayToDisk();
		}
		else
		{
			// If the input stream is not null then it will go through an
			// array of object and find the right audio track.
			try 
			{
				// Pass the audio track location to the fileInfo variable.
    			fileInfo = (ArrayList<FileInformation>) in.readObject();
    		} 
			catch (OptionalDataException e) 
			{
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} 
			catch (ClassNotFoundException e) 
			{
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} 
			catch (IOException e) 
			{
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
			
			// Remove the file path at this location.
			fileInfo.remove(position);
			
			// Display a message to the user that the file been deleted.
			Toast.makeText(getBaseContext(), "File deleted!", Toast.LENGTH_SHORT).show();
			
			// Save the new data after the file been deleted.
			saveArrayToDisk();
		}
		
		// Show a new list of the files.
		displayList();
	}
	
	/*
	 * This method save the file info to the data file.
	 */
	private void saveArrayToDisk()
	{
		try 
		{
			// Initialize and set a new data file.
			File file = new File(dataFilePath);
			
			// If the data file exists then delete it.
			if(file.exists())
				// This delete the file.
				file.delete();
			
			
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(dataFilePath));
			
			// Write the object to a file
			out.writeObject(fileInfo);
			out.flush();
			out.close();
		}
		catch(FileNotFoundException e)
		{
			Toast.makeText(getBaseContext(), "File Not Found.", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		catch(IOException e)
		{
			Toast.makeText(getBaseContext(), "IO Exception.", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		catch(Exception e)
		{
			Toast.makeText(getBaseContext(), "Exception!", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}
	
	/*
	 * This method will delete all the audio track saved from this program.
	 */
	private void deleteAllFiles()
	{
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() 
		{ 
  		   // @Override 
  		    public void onClick(DialogInterface dialog, int which) 
  		    { 
  		        switch (which)
  		        { 
  		        	case DialogInterface.BUTTON_POSITIVE: 
  		        											// The user selected yes
  		        											
  		        											// Initialize the integer variables.
                                    						int stringLength, arrayLength;
                                    						
                                    						// Initialize the string variables.
                                    						String fileName, fileNameSubstring;
                                    						
                                    						// Create a new folder. 
                                    						File mfile = new File(test_to_speech_directory + File.separatorChar);
                                    						
                                    						// Create an array of file in this folder.
                                    						File[] list = mfile.listFiles();
                                    						
                                    						// Pass the length of the list to the variable arrayLength.
                                    						arrayLength = list.length;
                                    						
                                    						// Delete everything in the folder.
                                    						for(int j = 0; j < arrayLength; j++)
                                    						{
                                    							fileName = list[j].getName();
                                    							stringLength = fileName.length();
                                    							fileNameSubstring = fileName.substring(stringLength-3,stringLength);
                                    							
                                    							// Check to find the file extension that is a WAV file.
                                    							if(fileNameSubstring.equalsIgnoreCase("wav"))
                                    								
                                    								// Delete the file.
                                    								list[j].delete();
                                    						}
                                    						
                                    						// Pass this path to the string variable to store it.
                                    						String dataFilePath = test_to_speech_directory + File.separatorChar + "FileInformationFile.dat";
                                    						
                                    						// Create a new file with the file path.
                                    						File myFile = new File(dataFilePath);
                                    						
                                    						// This delete the data file path.
                                    						myFile.delete();
                                    						
                                    						// This clear the file information.
                                    						fileInfo.clear();
                                    						
                                    						// This saved the new array after the file been deleted.
                                    						saveArrayToDisk();
                                    						
                                    						// This will display the new list.
                                    						displayList();
                                    						
                                    						// Display a message to the user that the file been deleted.
                                    						Toast.makeText(getBaseContext(), "Files deleted!", Toast.LENGTH_SHORT).show();
                                    						break; 
  		 
  		            case DialogInterface.BUTTON_NEGATIVE: 
                                    						// Display a message to the user that no files was deleted.
                                    						Toast.makeText(getBaseContext(), "No files deleted!", Toast.LENGTH_SHORT).show();
                                    						break; 
  		        } 
  		    } 
  		}; 
  		
  		// Initialize the file variable and create a folder.
  		File mfile1 = new File(test_to_speech_directory + File.separatorChar);
  		
  		// Create a new folder with a list of files.
        File[] list1 = mfile1.listFiles();
        
        // If the list length is longer than 1 file it ask the user if they want
        // to delete all the audio track from the list and if it not longer than 1 file
        // it will display a message that tell the user that there is no file to delete.
        if(list1.length > 1)
        {
        	// This is an alert message that ask if the user want to delete all the audio track.
        	AlertDialog.Builder builder = new AlertDialog.Builder(this); 
        	builder.setMessage("Are you sure you want to delete all your saved files?")
        	.setPositiveButton("Yes", dialogClickListener)
        	.setNegativeButton("No", dialogClickListener).show(); 
        }
        else
        {
        	// Display a message to the user that the list is empty and there nothing to delete.
            Toast.makeText(getBaseContext(), "The queue is empty. No files to delete!", Toast.LENGTH_SHORT).show();
        }
       
	}
	
	/*
	 * This method is auto generated.
	 */
	@Override
	protected void onDestroy() 
	{
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
}